import { Component, Vue, Watch } from 'vue-property-decorator'
import style from './AuthorizeApp.less'
import styles from '../NewApply/NewApply.less'
import OperationCol from '@/components/OperationCol'
import SealStatus from '@/components/SealStatus'
import { Action } from 'vuex-class'
import { ElTable } from 'element-ui/types/table'
import user from '@/lib/request/user'
import { IResponse } from '@/lib/service'
import UnAuthorized from '@/views/MyManagingSeal/UnAuthorized'
import TableEmpty from '@/components/tableEmpty'

export const projectStatus = [
  { key: 1, color: '#52C41A', text: '启用' },
  { key: 2, color: '#BFBFBF', text: '停用' },
]

export const APP_INTERFACE_TYPE: any = {
  1: 'Ukey签章',
  2: '云签章',
  3: 'Ukey签章',
  4: '云签章',
}

@Component({})
export default class AuthorizeApp extends Vue {
  private type: number = 0 // 0 云签章 1 Ukey
  authorized: number = 0 // 是否被授权印章管理员 1:授权 2:未授权
  private getTypeList: any[] = [
    { id: 0, name: '云签章应用' },
    { id: 1, name: 'Ukey签章应用' },
  ]
  private loading: boolean = false
  private projectId: string = ''
  private appName: string = ''
  private developer: string = ''
  private orgName: string = ''
  private appList: any[] = []
  private pageIndex: number = 1
  private pageSize: number = 10
  private total: number = 0
  private cascaderProps = {
    value: 'uuid',
    label: 'fullName',
    children: 'subList',
  }
  private options = []
  private area: string = ''
  private areaOption: any[] = []
  // readonly

  @Action('project/queryProjectManageSealAuthorizeList')
  private queryProjectManageSealAuthorizeList!: any
  @Action('applyPage/getAreas') private getAreas!: any
  // @Action('paymentOrder/queryByOrderId') private queryByOrderId!: any
  protected render() {
    return (
      <div class={[style.flex, { p10: this.authorized === 2 }]}>
        {this.authorized === 2 && (
          <UnAuthorized content="您尚未获得任何印章管理授权，无法查看印章的授权应用列表" />
        )}
        {this.authorized === 1 && (
          <div>
            <div class={style.tabs}>
              {this.getTypeList.map((type: any) => {
                return (
                  <p
                    class={{
                      [style.tabPane]: true,
                      [style.active]: type.id === this.type,
                    }}
                    onClick={() => {
                      this.typeChange(type.id)
                    }}
                  >
                    {type.name}
                  </p>
                )
              })}
            </div>
            {this.type === 1 && (
              <p class={style.tips}>
                <i class="el-icon-warning" />
                温馨提示：UKEY应用无需授权，可通过UKEY插入设备、输入PIN码直接使用。
              </p>
            )}
            <div
              class={[style.orderList, { [style.ukeyList]: this.type === 1 }]}
            >
              <div class={style.content}>
                <el-form ref="elform" class="search-form">
                  <div>
                    <el-row>
                      <el-col span={8}>
                        <el-form-item label="应用ID">
                          <el-input v-model={this.projectId} placeholder="" />
                        </el-form-item>
                      </el-col>
                      <el-col span={8}>
                        <el-form-item label="应用名称">
                          <el-input v-model={this.appName} placeholder="" />
                        </el-form-item>
                      </el-col>
                      <el-col span={8}>
                        <el-form-item label="应用主管单位">
                          <el-input v-model={this.orgName} placeholder="" />
                        </el-form-item>
                      </el-col>
                    </el-row>
                    <el-row>
                      <el-col span={8}>
                        <el-form-item label="应用开发单位">
                          <el-input v-model={this.developer} placeholder="" />
                        </el-form-item>
                      </el-col>
                      <el-col span={8}>
                        <el-form-item label="应用主管单位区域">
                          <el-cascader
                            ref="areaSelect"
                            v-model={this.areaOption}
                            placeholder="默认全部区域"
                            options={this.options}
                            // onVisible-change={this.areaOptionBlur}
                            show-all-levels={false}
                            {...{
                              props: { props: this.cascaderProps },
                            }}
                            clearable
                          />
                        </el-form-item>
                      </el-col>
                    </el-row>
                  </div>
                  <div>
                    <el-form-item>
                      <el-button
                        size="mini"
                        type="primary"
                        onClick={this.query}
                      >
                        搜索
                      </el-button>
                      <el-button size="mini" onClick={this.reset}>
                        重置
                      </el-button>
                    </el-form-item>
                  </div>
                </el-form>
                <p class="pt5">
                  {this.type === 0 && (
                    <el-button
                      class={['bg-color-blue', { [style.medium]: true }]}
                      onClick={this.authorizeApp}
                    >
                      授权新应用
                    </el-button>
                  )}
                </p>
                <div class={style.table}>
                  <el-table
                    data={this.appList}
                    v-loading={this.loading}
                    style="width: 100%"
                    ref="table"
                  >
                    <TableEmpty
                      v-show={!this.loading}
                      slot="empty"
                      msg={`当前查询条件下暂无已授权的${
                        this.type === 1 ? 'UKEY' : '云'
                      }签章应用`}
                    >
                      {this.type === 0 && (
                        <el-button type="primary" onClick={this.authorizeApp}>
                          前往授权新应用
                        </el-button>
                      )}
                    </TableEmpty>
                    <el-table-column
                      prop="iconUrl"
                      label="应用图标"
                      width="140"
                      align="center"
                      show-overflow-tooltip
                      {...{
                        scopedSlots: {
                          default: (scope: any) => {
                            return (
                              <el-image
                                style={{
                                  width: `71px`,
                                  height: `71px`,
                                }}
                                fit="scale-down"
                                src={
                                  scope.row.iconUrl ||
                                  require('@/assets/no-icon.svg')
                                }
                              />
                            )
                          },
                        },
                      }}
                    />
                    <el-table-column
                      prop="projectId"
                      label="应用ID"
                      min-width="90"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      prop="projectName"
                      label="应用名称"
                      min-width="110"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      prop="projectOrganizeName"
                      label="应用主管单位"
                      min-width="110"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      prop="developerName"
                      label="应用开发单位"
                      min-width="110"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      prop="validType"
                      label="对接方式"
                      min-width="100"
                      show-overflow-tooltip
                      {...{
                        scopedSlots: {
                          default: (scope: any) => {
                            return APP_INTERFACE_TYPE[scope.row.validType]
                          },
                        },
                      }}
                    />
                    <el-table-column
                      prop="sealAuthorizeCount"
                      label="已授权印章数量"
                      width="120"
                      show-overflow-tooltip
                    />
                    <el-table-column
                      prop="status"
                      label="状态"
                      min-width="80"
                      show-overflow-tooltip
                      {...{
                        scopedSlots: {
                          default: (scope: any) => {
                            return (
                              <SealStatus
                                statusData={projectStatus.find(
                                  item => scope.row.status === item.key
                                )}
                              />
                            )
                          },
                        },
                      }}
                    />
                    <el-table-column
                      prop="id"
                      label="操作"
                      width="230"
                      {...{
                        scopedSlots: {
                          default: (scope: any) => {
                            return (
                              <OperationCol
                                operations={this.filterOpera(scope.row)}
                                showNum={4}
                                row={scope.row}
                                index={scope.$index}
                              />
                            )
                          },
                        },
                      }}
                    />
                  </el-table>
                </div>

                {this.appList && this.appList.length > 0 && (
                  <el-pagination
                    class={{ [styles.pagination]: true }}
                    onSize-change={this.handleSizeChange}
                    onCurrent-change={this.handleCurrentChange}
                    current-page={this.pageIndex}
                    page-sizes={[10, 20, 30]}
                    page-size={this.pageSize}
                    layout="total, sizes, prev, pager, next, jumper"
                    total={this.total}
                    pager-count={5}
                  />
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    )
  }

  handleSizeChange(val: number) {
    this.pageIndex = 1
    this.pageSize = val
    this.queryList()
  }

  handleCurrentChange(val: number) {
    this.pageIndex = val
    this.queryList()
  }

  async queryList() {
    this.loading = true
    await this.$nextTick()
    await this.queryProjectManageSealAuthorizeList({
      pageIndex: this.pageIndex,
      pageNumber: this.pageSize,
      developerName: this.developer,
      projectId: this.projectId,
      projectName: this.appName,
      projectOrganizeName: this.orgName,
      sealUseType: this.type === 1 ? 1 : 2,
      organizeUuid: this.area,
    })
      .then((res: any) => {
        this.appList = (res || {}).list || []
        this.total = res.total
      })
      .catch(() => {})
    await this.$nextTick()
    this.loading = false
    const table = this.$refs.table as ElTable
    table.doLayout()
  }

  @Watch('areaOption')
  private areaOptionChange(val: any) {
    this.area = (typeof val === 'object' ? val[val.length - 1] : val) || ''
  }

  typeChange(id: number) {
    // 点击tab切换
    this.type = id
    this.$router.replace({
      name: 'authorizeApp',
      params: { type: id === 1 ? 'ukey' : 'cloud' },
    })
    this.reset()
  }
  async created() {
    this.type = (this.$route.params.type as any) === 'ukey' ? 1 : 0
    if (
      this.$route.params.type !== 'ukey' &&
      this.$route.params.type !== 'cloud'
    ) {
      this.$router.replace({ name: 'authorizeApp', params: { type: 'cloud' } })
    }
    await this.checkIsAuthManager()
    if (this.authorized === 1) {
      this.getAreas().then((data: any) => {
        this.options = data
      })
      this.query()
    }
  }

  async checkIsAuthManager() {
    const data: IResponse = await user.checkIsAuthManager()
    this.authorized = data.data ? 1 : 2
  }

  filterOpera(row: any) {
    const opt = [
      {
        id: 1,
        text: '详情',
        onClick: (index: number, rows: any) => {
          this.detail(rows)
        },
      },
    ]
    if (this.type === 0) {
      return opt.concat([
        {
          id: 1,
          text: '授权印章',
          onClick: (index: number, rows: any) => {
            this.editSeal(rows, 'auth')
          },
        },
        {
          id: 2,
          text: '取消授权',
          onClick: (index: number, rows: any) => {
            this.editSeal(rows, 'cancel')
          },
        },
      ])
    }

    return opt.concat([
      {
        id: 1,
        text: '查看授权印章',
        onClick: (index: number, rows: any) => {
          this.detailSeal(rows)
        },
      },
    ])
  }

  detail(row: any) {
    this.$router.push({
      name: 'projectDetail',
      query: { id: row.projectId },
    })
  }

  editSeal(row: any, type: string) {
    this.$router.push({
      name: 'authorizeUpdate',
      params: { type },
      query: {
        id: row.projectId,
        name: row.projectName,
        projectOrganizeName: row.projectOrganizeName,
        developerName: row.developerName,
      },
    })
  }

  detailSeal(row: any) {
    this.$router.push({
      name: 'authorizeAppSeal',
      query: { id: row.projectId, name: row.projectName },
    })
  }

  query() {
    this.pageIndex = 1
    this.total = 0
    this.appList = []
    this.queryList()
  }

  reset() {
    this.appName = ''
    this.developer = ''
    this.orgName = ''
    this.projectId = ''
    this.area = ''
    this.areaOption = []
    this.query()
  }

  authorizeApp() {
    this.$router.push({ name: 'authorizeNew' })
  }
}
